
// Definition for singly-linked list.
function ListNode(val) {
    this.val = val;
    this.next = null;
}

/**
 * @param {ListNode} head
 * @param {number} val
 * @return {ListNode}
 */
var deleteNode = function(head, val) {
  if(!head) return null;
  if(!head.next) {
    return head.val == val ? null : head;
  }
  let last = head;
  while(head && head.val == val) {
    let node = head;
    delete node;
    head = head.next;
    last = head;
  }
  if(!head.next) return head;
  let temp = head.next;
  while(temp) {
    if(temp.val == val) {
      let node = temp;
      last.next = temp.next;
      temp = temp.next;
      delete node;
      continue;
    } else {
      last = last.next;
      temp = temp.next;
    }
  }
  return head;
};
let head = [4,5,1,9], val = 5;
console.log(deleteNode(head, val));
head = [4,5,1,9], val = 1;
console.log(deleteNode(head, val));
